Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PEP 695] Allow Self return types with contravariance #17786

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

JukkaL
Copy link
Collaborator

@JukkaL JukkaL commented Sep 19, 2024

Fix variance inference in this fragment from a typing conformance test:

class ClassA[T1, T2, T3](list[T1]):
    def method1(self, a: T2) -> None:
        ...

    def method2(self) -> T3:
        ...

Previously T2 was incorrectly inferred as invariant due to list having methods that return Self. Be more flexible with return types to allow inferring contravariance for type variables even if there are Self return types, in particular.

We could probably make this even more lenient, but after thinking about this for a while, I wasn't sure what the most general rule would be, so I decided to just make a tweak to support the likely most common use case (which is probably actually not that common either).

Link to conformance test:
https://github.com/python/typing/blob/main/conformance/tests/generics_variance_inference.py#L15C1-L20C12

Fix variance inference in this fragment from a typing conformance test:
```
class ClassA[T1, T2, T3](list[T1]):
    def method1(self, a: T2) -> None:
        ...

    def method2(self) -> T3:
        ...
```

Previously T2 was incorrectly inferred as invariant due to `list` having
methods that return `Self`. Be more flexible with return types to allow
inferring contravariance for type variables even if there are `Self` return
types, in particular.

We could probably make this even more lenient, but after thinking about
this for a while, I wasn't sure what the most general rule would be, so
I decided to just make a tweak to support the likely most common use case
(which is probably actually not that common either).

Link to conformance test:
https://github.com/python/typing/blob/main/conformance/tests/generics_variance_inference.py#L15C1-L20C12

This comment has been minimized.

@JukkaL
Copy link
Collaborator Author

JukkaL commented Sep 19, 2024

The build failure looks like a flake.

Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant